package com.github.eclipseace.mybatis.entity.mapper;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;

import com.github.eclipseace.mybatis.pagination.PaginationInterceptor;
import com.github.eclipseace.mybatis.util.Assert;
import com.github.eclipseace.mybatis.util.BuilderUtils;

/**
 * @author eclipseAce
 */
public class StatementApplier {
	private final Configuration configuration;
	private final String sourceId;
	private final String targetId;

	public StatementApplier(Configuration configuration, String sourceId, String targetId) {
		this.configuration = configuration;
		this.sourceId = sourceId;
		this.targetId = targetId;
	}

	protected void copyIfAbsent(String suffix) {
		String actualSourceId = sourceId;
		String actualTargetId = targetId;
		if (suffix != null) {
			actualSourceId += suffix;
			actualTargetId += suffix;
		}
		if (configuration.hasStatement(actualSourceId) && !configuration.hasStatement(actualTargetId)) {
			MappedStatement source = configuration.getMappedStatement(actualSourceId);
			MappedStatement target = BuilderUtils.buildFrom(source, actualTargetId)
					.build();
			configuration.addMappedStatement(target);
		}
	}

	public void applyIfAbsent() {
		Assert.isTrue(configuration.hasStatement(sourceId), "No entity statement [" + sourceId + "] found");

		copyIfAbsent(null);
		// Copy pagination statements
		copyIfAbsent(PaginationInterceptor.PAGE_STATEMENT_ID_SUFFIX);
		copyIfAbsent(PaginationInterceptor.TOTAL_STATEMENT_ID_SUFFIX);
	}
}
